package com.google.code.flickrlite;

import java.util.ArrayList;
import java.util.List;

public class UrlBuilder {

	private final static String URL_FORMAT = "%s://%s%s?%s";

	public final static String PROTO_HTTP = "http";
	public final static String PROTO_HTTPS = "https";

	public final static String DEFAULT_PATH = "/";

	private String proto;
	private String host;
	private String path;

	private List<NameValuePair> queryParams = new ArrayList<NameValuePair>();

	private class NameValuePair {

		private final String name;
		private final String value;

		public NameValuePair(String name, String value) {
			this.name = name;
			this.value = value;
		}

		public String getName() {
			return name;
		}

		public String getValue() {
			return value;
		}

	}

	public UrlBuilder(String proto, String host, String path) {

		this.proto = proto != null ? proto : PROTO_HTTP;
		this.host = host;
		this.path = path != null ? path : DEFAULT_PATH;
	}

	public UrlBuilder(String host, String path) {
		this(null, host, path);
	}

	public void addQueryParam(String name, String value) {
		queryParams.add(new NameValuePair(name, value));
	}

	public void clearQueryParams() {
		queryParams.clear();
	}

	public String getURL() {
		return String.format(URL_FORMAT, proto, host, path,
				getQueryParamsString());
	}

	private String getQueryParamsString() {

		StringBuffer stringBuffer = new StringBuffer();

		boolean first = true;

		for (NameValuePair nvPair : queryParams) {
		
			if (first) {
				first = false;
			} else {
				stringBuffer.append('&');
			}
			
			stringBuffer.append(nvPair.getName());
			stringBuffer.append('=');
			stringBuffer.append(nvPair.getValue());
		}

		return stringBuffer.toString();
	}
}
